#!/usr/bin/env python
# -*- coding: utf-8 -*-
import timeit
import datetime as dt
import os.path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


def all_day_line_graph(bus):#line = 10 or 15
    x = []
    y = []
#     input_file = os.path.join('..','..','resource','result_day_%d.txt' % bus)
    input_file = os.path.join('file','day.txt')
    counter = 0
    with open(input_file, 'r') as f:
        for line in f:
            arr = line.strip().split(',')
            #10, 20140801, 44256, 晴, 36, 雷阵雨, 26
#             x.append(counter)
            y.append(int(arr[2]))
            counter += 1
    f.close()
    dates = mdates.drange(dt.datetime(2014, 8, 1), dt.datetime(2015,1,1), 
                          dt.timedelta(days=1))
    fig, ax = plt.subplots(figsize=(15, 9))
    ax.bar(dates, y)
    ax.xaxis_date()
    fig.autofmt_xdate()
    plt.title('Total Number of Passangers Taking Line No.%d by Day' % bus)
#     plt.show()
    img = os.path.join('img', 'day_sum.png')
    fig.savefig(img, bbox_inches='tight')   
    


    
def test():
    dates = mdates.drange(dt.datetime(2014, 8, 1), dt.datetime(2014,12,31), 
                          dt.timedelta(weeks=1))
    counts = np.sin(np.linspace(0, np.pi, dates.size))
    fig, ax = plt.subplots()
    width = np.diff(dates).min()
    
    ax.bar(dates, counts, align='center', width=width)
    ax.xaxis_date()
    fig.autofmt_xdate()
    
    plt.show()  

def day_type():   
    num_of_every_type = [[],[],[],[],[],[],[]]
    
    with open("format/day_type.txt", 'r') as f:
        feature_names = f.readline().split()
        for line in f:
            arr = line.strip().split('\t')
            #20140801    7    2    5    1    36    5    26    281
            num_of_every_type[int(arr[3])-1].append(arr[8])
#     X = data[:, 1:]  # select columns 1 through end
#     print X.shape
#     print X [:10]
#     y = data[:, 0]
#     print y.shape  
#     print feature_names
    
    dates = mdates.drange(dt.datetime(2014, 8, 1), dt.datetime(2015,1,1), 
                          dt.timedelta(days=1))
    fig, ax = plt.subplots(figsize=(18, 9))
    
    for type in num_of_every_type:
        plt.plot(dates, type)
    ax.xaxis_date()
    fig.autofmt_xdate()
    plt.legend(['ordinary', 'the old', 'students', 'staff', \
                'the disabled', 'supervisors', 'soldiers'], loc='center right')
    plt.grid()
    plt.show()
    img = os.path.join('img', 'day_type.png')
    fig.savefig(img, bbox_inches='tight') 

def hour():
    X = []
    y = []
    with open("format/hour_complete.txt", 'r') as f:
        feature_names = f.readline().split()
        for line in f:
            arr = line.strip().split('\t')
            X.append(arr[0] + ' ' + arr[1])
            y.append(arr[-1])
    f.close()
    
    dates = mdates.drange(dt.datetime(2014, 8, 1, 5), dt.datetime(2014,8,1,23), 
                          dt.timedelta(hours=1))
    print len(dates)
    for i in range(2, 32):
        dates = np.append(dates, (mdates.drange(dt.datetime(2014, 8, i, 5), dt.datetime(2014,8, i, 23), 
                          dt.timedelta(hours=1))))
    print len(dates)
    for i in range(1, 31):
        dates = np.append(dates, (mdates.drange(dt.datetime(2014, 9, i, 5), dt.datetime(2014,9,i,23), 
                          dt.timedelta(hours=1))))
    print len(dates)
    for i in range(1, 32):
        dates = np.append(dates, (mdates.drange(dt.datetime(2014, 10, i, 5), dt.datetime(2014,10,i,23), 
                          dt.timedelta(hours=1))))
    print len(dates)
    for i in range(1, 31):
        dates = np.append(dates, (mdates.drange(dt.datetime(2014, 11, i, 5), dt.datetime(2014,11,i,23), 
                          dt.timedelta(hours=1))))
    print len(dates)
    for i in range(1, 32):
        dates = np.append(dates, (mdates.drange(dt.datetime(2014, 12, i, 5), dt.datetime(2014,12,i,23), 
                          dt.timedelta(hours=1))))
    print len(dates)
    
    fig, ax = plt.subplots(figsize=(18, 9))
    ax.xaxis_date()
    fig.autofmt_xdate()
    print len(dates), len(y)
    plt.plot(dates, y)
    plt.grid()
#     plt.show()
    img = os.path.join('img', 'hour.png')
    fig.savefig(img, bbox_inches='tight') 
    
def hour_a_day():#line = 10 or 15
    x = []
    y = []
#     input_file = os.path.join('..','..','resource','result_day_%d.txt' % bus)
    input_file = os.path.join('format','hour.txt')
    counter = 0
    with open(input_file, 'r') as f:
        f.readline()
        for line in f:
            print line
            if counter == 18:
                break
            arr = line.strip().split('\t')
            #20140801    5    5    0    1    36    37
            y.append(int(arr[6]))
            counter += 1
    f.close()
    fig, ax = plt.subplots(figsize=(15, 9))
    ax.bar([i for i in range(5, 23)], y)
#     plt.title('Total Number of Passangers Taking Line No.%d by Day' % bus)
#     plt.show()
    img = os.path.join('img', 'hour_a_day.png')
    fig.savefig(img, bbox_inches='tight')   

def hour_type():   
    num_of_every_type = [[],[],[],[],[],[],[]]
    
    counter = 0
    with open("format/hour_type.txt", 'r') as f:
        feature_names = f.readline().split()
        for line in f:
            if counter == 18 * 7:
                break
            arr = line.strip().split('\t')
            #20140801    5    4    5    0    1    36    2
            num_of_every_type[int(arr[2])-1].append(arr[7])
            counter += 1
#     X = data[:, 1:]  # select columns 1 through end
#     print X.shape
#     print X [:10]
#     y = data[:, 0]
#     print y.shape  
#     print feature_names
    
    fig, ax = plt.subplots(figsize=(18, 9))
    
    for type in num_of_every_type:
        plt.plot([i for i in range(5, 23)], type)
    plt.legend(['ordinary', 'the old', 'students', 'staff', \
                'the disabled', 'supervisors', 'soldiers'], loc='upper right')
    plt.grid()
#     plt.show()
    img = os.path.join('img', 'hour_type.png')
    fig.savefig(img, bbox_inches='tight') 
    
def weather():   
    num_of_every_type = [[],[],[],[],[]]
    
    with open("format/day_with_noise.txt", 'r') as f:
        feature_names = f.readline().split()
        for line in f:
            arr = line.strip().split()
            #20140801    5    0    1    36    5    26    44256
            num_of_every_type[0].append(arr[4])
            num_of_every_type[1].append(arr[6])
            num_of_every_type[2].append(arr[3])
            num_of_every_type[3].append(arr[5])
            num_of_every_type[4].append(int(arr[7])/1000.0)
    print num_of_every_type[4]
    dates = mdates.drange(dt.datetime(2014, 8, 1), dt.datetime(2015,1,1), 
                          dt.timedelta(days=1))
    fig, ax = plt.subplots(figsize=(18, 9))
    
    for type in num_of_every_type:
        plt.plot(dates, type)
    ax.xaxis_date()
    fig.autofmt_xdate()
    plt.legend(['max temperature', 'max min', 'weather of day', \
                'weather of night', 'passengers'],
               loc='upper left')
    plt.grid()
#     plt.show()
    img = os.path.join('img', 'weather.png')
    fig.savefig(img, bbox_inches='tight') 

def main():
#     all_day_line_graph(10)
#     all_day_line_graph(15)
#     test()
#     day_type()
#     hour()
#     hour_a_day()
#     hour_type()
    weather()

if __name__ == '__main__':
    start = timeit.default_timer()
    
    main()
    
    stop = timeit.default_timer()
    print 'run time: %.10fs' % (stop - start)
    
